import {Component, HostListener, OnDestroy, OnInit} from "@angular/core";
import {sjgzxinModuledatas} from "../pubcomponent/pageTitle.datas";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {MyValidator} from "../myvalidator-util";

declare var $: any;

@Component({
  template: `
  <div class="all_bg paddingTop">
    <div class="">
      <div class="marginBottom">
        <ng-container *ngIf="actionobj1.length">
          <portlet-action class="actions" [o]="actionobj1" (outhander)="actionHander($event)"></portlet-action>
        </ng-container>
      </div>
      <div class="portlet-body">
        <div class="row">
          <div class="form-horizontal" role="form">
            <div class="col-lg-offset-5 col-lg-3">
              <div class="form-group">
                <label class="col-lg-3 control-label">车牌号</label>
                <div class="col-lg-8">
                  <input type="text" class="form-control" name="cph" [(ngModel)]="s_obj.cph"/>
                </div>
              </div>
            </div>
            <div class="col-lg-3">
              <div class="form-group">
                <label class="control-label col-lg-5">是否关联运送任务</label>
                <div class="col-lg-7">
                  <select class="form-control" id="sfglrwSelect" name="sfglrw" [(ngModel)]="s_obj.sfglrw"
                          (change)="inittable_car()"></select>
                </div>
              </div>
            </div>
            <div class="col-lg-1">
              <button type="button" class="btn blue" (click)="inittable_car()"><i class="fa fa-search"></i> 搜索</button>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-12" *ngIf="table_car">
            <my-table [o]="table_car"></my-table>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="xq_carModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">详情</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-lg-12" *ngIf="xqobj_car">
                <xq-form [o]="xqobj_car"></xq-form>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">确 定</button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="add_carModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">{{modaltitle}}</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="form-horizontal" role="form" [formGroup]="formgroup_car">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">
                      <require-label></require-label>
                      车牌号：</label>
                    <div class="col-lg-8">
                      <input type="text" class="form-control" formControlName="cphCtr"/>
                      <div
                        *ngIf="formgroup_car.get('cphCtr').invalid&&formgroup_car.get('cphCtr').dirty">
                          <span *ngIf="formgroup_car.hasError('myrequire','cphCtr')">
                                <tool-tip [o]="formgroup_car.getError('myrequire','cphCtr').msg"></tool-tip>
                          </span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">
                      <require-label></require-label>
                      车辆品牌：
                    </label>
                    <div class="col-lg-8">
                      <input type="text" class="form-control" formControlName="clppCtr"/>
                      <div
                        *ngIf="formgroup_car.get('clppCtr').invalid&&formgroup_car.get('clppCtr').dirty">
                          <span *ngIf="formgroup_car.hasError('myrequire','clppCtr')">
                                <tool-tip [o]="formgroup_car.getError('myrequire','clppCtr').msg"></tool-tip>
                          </span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">
                      <require-label></require-label>
                      车型:
                    </label>
                    <div class="col-lg-8">
                      <input type="text" class="form-control" formControlName="cxCtr"/>
                      <div *ngIf="formgroup_car.get('cxCtr').dirty&&formgroup_car.get('cxCtr').invalid">
                          <span *ngIf="formgroup_car.hasError('myrequire','cxCtr')">
                             <tool-tip [o]="formgroup_car.getError('myrequire','cxCtr').msg"></tool-tip>
                          </span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="control-label col-lg-3">
                      <require-label></require-label>
                      车辆来源:
                    </label>
                    <div class="col-lg-8">
                      <input type="text" class="form-control" formControlName="cllyCtr"/>
                      <div *ngIf="formgroup_car.get('cllyCtr').dirty&&formgroup_car.get('cllyCtr').invalid">
                          <span *ngIf="formgroup_car.hasError('myrequire','cllyCtr')">
                             <tool-tip [o]="formgroup_car.getError('myrequire','cllyCtr').msg"></tool-tip>
                          </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
            <button type="button" class="btn btn-primary" (click)="addsure_car()">确 定</button>
          </div>
        </div>
      </div>
    </div>
    </div>
  `
})
export class CarglComponent implements OnInit, OnDestroy {
  pagetitleobj: any;
  userinfo: any;
  s_obj: any = {
    cph: "",
    sfglrw: ""
  };
  table_car: any;
  car_btns: any[] = ["car_add", "car_refresh"];
  car_c_btns: any[] = ["xq_car", "edite_car", "remove_car"];
  hascbtns: any[] = [];
  actionobj1: any[] = [];
  caozuo_carbh: string;
  xqobj_car: any;
  formgroup_car: FormGroup;
  modaltitle: string = "";
  modalflag: string;

  /**
   * 初始化按钮
   */
  initactions(): void {
    // this.commservice.getroleBtns(this.car_btns, this.car_c_btns, this.userinfo.nowroleid, "tablecar", (hasportbtns, hastablebtns) => {
    //   this.actionobj1 = hasportbtns;
    //   this.hascbtns = hastablebtns;
    // });
    this.commservice.getroleBtns_not_permissions(this.car_btns, this.car_c_btns, "tablecar", (hasportbtns, hastablebtns) => {
      this.actionobj1 = hasportbtns;
      this.hascbtns = hastablebtns;
    });
  }

  /**
   * 按钮的处理回调
   * @param e
   */
  actionHander(e: any): void {
    const fromv = e.pfrom;
    const actiontype = e.type;
    if (fromv === "tablecar") {
      if (actiontype === "refresh") {
        // 刷新
        this.table_car = Object.assign({}, this.table_car);
      } else if (actiontype === "add") {
        // 添加
        this.add_car();
      }
    }
  }

  /**
   * 添加
   */
  add_car(): void {
    this.modalflag = "add";
    this.modaltitle = "添加运送车辆";
    this.formgroup_car.reset();
    $("#add_carModal").modal({
      keyboard: true,
      backdrop: "static"
    });
  }

  inittable_car(): void {
    const that = this;
    this.table_car = {
      tableid: "table_car",
      url: "sjgz/jcsj/sjcllb",
      reqobj: this.s_obj,
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      total: "totalRows",
      rows: "sjclList",
      columns: [{
        checkbox: true,
        visible: false
      }, {
        title: "序号",
        field: "ordernum",
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        }
      }, {
        title: "车牌号",
        field: "cph",
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        }
      }, {
        title: "车型",
        field: "cx",
        cellStyle: function () {
          return {
            classes: 'td3'
          }
        }
      }, {
        title: "车辆品牌",
        field: "clpp",
        cellStyle: function () {
          return {
            classes: 'td4'
          }
        }
      }, {
        title: "车辆来源",
        field: "clly",
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        }
      }, {
        title: "创建机构名称",
        field: "cjjgmc",
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        }
      }, {
        title: "操作",
        field: "sjclbh",
        events: this.myevents,
        formatter: function (value, row, index) {
          let str: string = "";
          const islock = row.kdsfkbj;
          if (that.hascbtns.indexOf("edite_car") != -1) {
            str += "<button type='button' class='btn btn-xs btn-primary edite_car'><i class='fa fa-pencil'></i> 编辑</button>";
          }

          if (that.hascbtns.indexOf("remove_car") != -1) {
            str += "<button type='button' class='btn btn-xs btn-warning remove_car'><i class='fa fa-trash'></i> 删除</button>";
          }

          if (that.hascbtns.indexOf("xq_car") != -1) {
            str += "<button type='button' class='btn btn-xs btn-info xq_car'><i class='fa fa-search'></i> 详情</button>";
          }
          return str;
        }
      }]
    };
      // this.table_car.pageSize = 50;
      // this.table_car.pageList = [50];
      // this.table_car.hiddenPageinfoLink = true;
      // this.table_car.paginationLoop = true;
      // this.table_car.paginationPreText = "<i class='fa fa-arrow-left'></i>上一页";
      // this.table_car.paginationNextText = "下一页<i class='fa fa-arrow-right'></i>";
      // this.table_car.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50;
      this.table_car.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50;
  }

  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .xq_car": function (e, value, row, index) {
      this.caozuo_carbh = value;
      this.xq_car();
    }.bind(this),
    "click .remove_car": function (e, value, row, index) {
      this.caozuo_carbh = value;
      if (!this.caozuo_carbh) {
        return
      }
      this.commservice.myswal("warning", "确定删除？", "", "cz", () => {
        this.removeDone_car();
      });
    }.bind(this),
    "click .edite_car": function (e, value, row, index) {
      this.caozuo_carbh = value;
      this.edite_car(row);
    }.bind(this),
  }


  /**
   * 详情
   */
  xq_car(): void {
    if (!this.caozuo_carbh) {
      return
    }
    const url = "sjgz/jcsj/sjclxq";
    this.itservice.kwPtPost(url, {
      sjclbh: this.caozuo_carbh
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            this.xqobj_car = {
              from: "carxin",
              keyValue: resp,
            };
            $("#xq_carModal").modal({
              keyboard: true,
              backdrop: "static"
            });
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.xq_car();
        }
      });
    })
  }

  /**
   * 单条删除
   */
  removeDone_car(): void {
    const url = "sjgz/jcsj/sjclsc";
    this.itservice.kwPtPost(url, {
      sjclbhs: [this.caozuo_carbh]
    }).subscribe(resp => {
      this.commservice.handResponse("put", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            this.commservice.myswal("success", resp, "", "ts", null);
            this.table_car = Object.assign({}, this.table_car);
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.removeDone_car();
        }
      });
    });
  }


  /**
   * 表单
   */
  createformgroup_car(): void {
    this.formgroup_car = this.fb.group({
      cphCtr: ["", [this.myValidator.myrequired('车牌号')]],
      clppCtr: ["", [this.myValidator.myrequired("车辆品牌")]],
      cxCtr: ["", [this.myValidator.myrequired("车型")]],
      cllyCtr: ["", [this.myValidator.myrequired("车辆来源")]]
    });
  }

  /**
   * 编辑
   */
  edite_car(row: any): void {
    this.modalflag = "edite";
    this.modaltitle = "编辑运送车辆";
    const cphv = row.cph;
    const clppv = row.clpp;
    const cxv = row.cx;
    const cllyv = row.clly;
    this.formgroup_car.patchValue({
      cphCtr: cphv,
      clppCtr: clppv,
      cxCtr: cxv,
      cllyCtr: cllyv
    });
    $("#add_carModal").modal({
      keyboard: true,
      backdrop: "static"
    });
  }

  /**
   * 验证+保存
   */
  addsure_car(): void {
    if (this.formgroup_car.invalid) {
      const ctrols = this.formgroup_car.controls;
      for (let path in ctrols) {
        ctrols[path].markAsDirty();
        ctrols[path].updateValueAndValidity();
      }
      return
    }
    const formgroupv = this.formgroup_car.getRawValue();
    const cphv = this.commservice.removeSpace(true, formgroupv.cphCtr);
    const clppv = this.commservice.removeSpace(true, formgroupv.clppCtr);
    const cxv = this.commservice.removeSpace(true, formgroupv.cxCtr);
    const cllyv = this.commservice.removeSpace(true, formgroupv.cllyCtr);
    const actionflag = this.modalflag;
    this.commservice.blockUI({
      boxed: true,
      message: "保存中...",
      zIndex: 10051,
      overlayColor: "#67809F"
    });
    if (actionflag == "add") {
      const url = 'sjgz/jcsj/sjclxz';
      this.itservice.kwPtPost(url, {
        cph: cphv,
        clpp: clppv,
        cx: cxv,
        clly: cllyv
      }).subscribe(resp => {
        this.commservice.handResponse("put", url, resp, (arg1, resp, arg2) => {
          if (arg1) {
            if (arg2) {
              this.commservice.myswal("success", resp, "", "ts", null);
              this.table_car = Object.assign({}, this.table_car);
              $("#add_carModal").modal("hide");
            } else {
              this.commservice.myswal("warning", resp, "", "ts", null);
            }
          } else {
            this.addsure_car();
          }
        });
      })
    } else if (actionflag == "edite") {
      const url = "sjgz/jcsj/sjclxg";
      this.itservice.kwPtPost(url, {
        sjclbh: this.caozuo_carbh,
        cph: cphv,
        clpp: clppv,
        cx: cxv,
        clly: cllyv
      }).subscribe(resp => {
        this.commservice.handResponse("put", url, resp, (arg1, resp, arg2) => {
          if (arg1) {
            if (arg2) {
              this.commservice.myswal("success", resp, "", "ts", null);
              this.table_car = Object.assign({}, this.table_car);
              $("#add_carModal").modal("hide");
            } else {
              this.commservice.myswal("warning", resp, "", "ts", null);
            }
          } else {
            this.addsure_car();
          }
        })
      });
    }
  }

  /**
   * 处理搜索表单
   */
  createsearchForm(): void {
    // 是否关联押运任务
    const datalist = [{
      code: "0",
      name: "已关联"
    }, {
      code: "1",
      name: '未关联'
    }];
    $("#sfglrwSelect").empty();
    let str: string = "<option value=''>--请选择--</option>";
    datalist.forEach((item) => {
      str += "<option value='" + item.code + "'>" + item.name + "</option>";
    });
    $("#sfglrwSelect").append(str);
    $("#sfglrwSelect").selectpicker({
      size: 5
    });
    this.s_obj.sfglrw = ""; // 全部
  }

  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      this.initactions(); //用户按钮权限
    });
  }

  constructor(private commservice: CommService,
              private itservice: MyhttpService,
              private fb: FormBuilder,
              private myValidator: MyValidator) {

  }

  ngOnInit() {
    this.pagetitleobj = sjgzxinModuledatas.cargl;
    this.getuserinfo();
    this.createsearchForm();
    this.inittable_car();
    this.createformgroup_car();
  }

  ngOnDestroy() {

  }

}
